<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ this.$router.currentRoute.name }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-page-header @back="goBack"
                      :content="this.$router.currentRoute.name.substring(this.$router.currentRoute.name.indexOf('/')+1)">
      </el-page-header>
      <!-- 系统通知列表卡片区 -->
      <el-form :inline="true" ref="form" size="small" style="margin-top: 2vh">
        <el-row>
          <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">条件查询区</h4>
          <el-form-item>
            操作账户：
            <el-select
                clearable
                style="width: 140px;"
                filterable
                placeholder="请选择操作账户"
                v-model="queryMap.accountName"
                @change="changeAccountName"
            >
              <el-option
                  v-for="(name) in accountName"
                  :key="name"
                  :label="name"
                  :value="name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-form-item>
          <el-input
              style="width: 140px;"
              v-model="queryMap.resourceName"
              clearable
              placeholder="请输入客户名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
              style="width: 150px;"
              v-model="queryMap.linkman"
              clearable
              placeholder="请输入联系人名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
              style="width: 130px;"
              v-model="queryMap.phoneA"
              clearable
              placeholder="请输入电话"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
              v-model="queryMap.industryId"
              clearable
              style="width: 140px;"
              placeholder="请选择行业类别"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option
                v-for="IndustryVO in IndustryVOs"
                :label="IndustryVO.options"
                :key="IndustryVO.industryId"
                :value="IndustryVO.industryId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
              clearable
              style="width: 140px;"
              v-model="queryMap.clientTypeId"
              placeholder="请选择客户种类"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option
                v-for="clientTypeVo in clientTypeVos"
                :label="clientTypeVo.options"
                :key="clientTypeVo.clientTypeId"
                :value="clientTypeVo.clientTypeId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryMap.userId" style="width: 140px;" filterable placeholder="请选择归属人">
            <el-option label="全部" value="-1"></el-option>
            <el-option
                v-for="item in options_user"
                :key="item.userId"
                :label="item.nickName+'('+item.userName+')'"
                :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
              clearable
              style="width: 140px;"
              v-model="queryMap.isCall"
              placeholder="是否呼叫"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间筛选:">
          <el-select
              clearable
              style="width: 120px;"
              v-model="queryMap.time"
              placeholder="请选择时间"
          >
            <el-option label="创建时间" value="1"></el-option>
            <el-option label="呼叫时间" value="2"></el-option>
            <el-option label="更新时间" value="3"></el-option>
          </el-select>
          <el-date-picker
              v-model="value2"
              type="daterange"
              align="right"
              format="yyyy-MM-dd"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="reset" icon="el-icon-refresh">重置</el-button>
          <el-button @click="searchClient()" type="primary" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>

      <div style="margin-bottom: 10px;display: flex">
        <span class="hint" style="flex: 1;"></span>
        <el-button style="" icon="el-icon-top-right" v-hasPermission="'customer:shift'"
                   @click="showElectUsersBox">批量转移
        </el-button>
      </div>
      <!-- 表格区域 -->
      <el-table ref="multipleTable" :data="clientData" size="small" @selection-change="handleSelectionChange"
                border style="width: 100%;" height="420">
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="accountName" label="账户" width="100" fixed="left"></el-table-column>
        <el-table-column prop="resourceName" label="客户名称" width="116"></el-table-column>
        <el-table-column prop="linkman" label="联系人" width="100"></el-table-column>
        <el-table-column prop="phoneA" label="电话A" width="100"></el-table-column>
        <el-table-column prop="phoneB" label="电话B" width="100"></el-table-column>
        <el-table-column prop="clientType" label="客户种类" width="100"></el-table-column>
        <el-table-column label="生命周期" width="100">
          <template slot-scope="scope">
            <span>
          {{
                scope.row.lifeCycle === 0 ? '潜在' :
                    scope.row.lifeCycle === 1 ? '签约' :
                        scope.row.lifeCycle === 2 ? '重复购买' :
                            scope.row.lifeCycle === 3 ? '失效' :
                                '未知'
              }}
        </span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="客户来源" width="100"></el-table-column>
        <el-table-column prop="industryType" label="行业类型" width="100"></el-table-column>
        <el-table-column prop="nick_name" label="所属人" width="100"></el-table-column>
        <el-table-column prop="lastCallTime" label="最后呼叫时间" width="140"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="140"></el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNum"
          :page-sizes="this.$globalVar.sizes"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
      <!-- 选择用户窗口 -->
      <ElectUsersBox title="资源分配" @confirmUserId="confirmUserId" :isShow="electUsersBoxShow"
                     @updateElectUsersBoxShow="electUsersBoxShow=false"/>
    </el-card>
  </div>
</template>
<script>
import axios from "axios";
import ElectUsersBox from "@/components/electUsersBox.vue";

export default {
  components: {ElectUsersBox},
  data() {
    return {
      electUsersBoxShow: false,//选择用户窗口是否展示
      total: 0,
      multipleSelection: [],
      value2: '',//日期选择器
      clientData: [],
      IndustryVOs: [],
      clientTypeVos: [],
      options_user: [],
      //查询对象
      queryMap: {
        pageNum: 1,
        pageSize: 10,
        resourceName: "",
        linkman: "",
        phoneA: "",
        industryId: "",
        clientTypeId: "",
        userId: "",
        isCall: "",
        time: '1',
        startTime: "",
        endTime: "",
        accountName:""
      },
      updateForm: {},
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

    };
  },
  methods: {
    changeAccountName() {
      this.getClientList();
      this.getAllIndustryList();
      this.getAllClientType();
    },
    showElectUsersBox() {
      //判断是否有选中的客户
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请选择客户");
        return;
      }
      this.electUsersBoxShow = true;
    },
    /**
     * 退一步
     */
    goBack() {
      console.log('go back');
    },
    /**
     * 重置
     */
    reset() {
      this.queryMap = {
        pageNum: 1,
        pageSize: 10,
        resourceName: "",
        linkman: "",
        phoneA: "",
        industryId: "",
        clientTypeId: "",
        userId: "",
        isCall: "",
        time: '1',
        startTime: "",
        endTime: "",
        accountName:""
      };
      this.defaultTime();
      this.getClientList();
    },

    searchClient() {
      this.queryMap.pageNum = 1;
      this.getTime();
      this.getClientList();
    },

    //加载客户列表
    async getClientList() {
      const {data: res} = await this.$http.get(
          "customer/findList",
          {
            params: this.queryMap
          }
      );
      if (!res.success) {
        return this.$message.error("获取用户列表失败:" + res.data.errorMsg);
      } else {
        this.total = res.data.total;
        this.clientData = res.data.rows;
      }
    },
    //加载行业类型列表
    async getAllIndustryList() {
      this.loading = true;
      const {data: res} = await this.$http.get("/customer/findIndustryVOList", {
        params: {accountName: this.queryMap.accountName}
      });
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.IndustryVOs = validData.map(item => ({
          industryId: item.industryId,
          options: item.options
        }));
      }
    },
    //加载客户类型列表
    async getAllClientType() {
      this.loading = true;
      const {data: res} = await this.$http.get("/customer/findClientTypeVOList",{
        params: {accountName: this.queryMap.accountName}
      });
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.clientTypeVos = validData.map(item => ({
          clientTypeId: item.clientTypeId,
          options: item.options
        }));
      }
    },
    //获取所有账户
    async getAccountNameList() {
      const {data: res} = await this.$http.get("/system/user/qt/findRoleList");
      if (!res.success) {
        return this.$message.error("获取角色信息失败:" + res.data);
      }
      this.accountName = res.data

    },
    /**
     * 加载归属人列表
     */
    async selectUser() {
      const {data: res} = await this.$http.post("/system/departmentUtils/getUserListByMap/", {});
      if (res.success) {
        this.options_user = res.data;
      } else {
        return this.$message.error("系统通知信息编辑失败:" + res.message);
      }
    },
    getTime() {
      if (this.value2 != null && this.value2.length === 2) {
        console.log("时间：", this.value2);
        // 格式化开始和结束时间
        this.queryMap.startTime = this.formatDate(this.value2[0], false); // 开始日期
        this.queryMap.endTime = this.formatDate(this.value2[1], true);    // 结束日期
      } else {
        this.queryMap.startTime = "";
        this.queryMap.endTime = "";
      }
    },
// 定义一个格式化时间的函数（格式为 yyyy-MM-dd）
    formatDate(date, isEnd) {
      if (date != null) {
        let formattedDate = new Date(date); // 复制一份新的日期对象，避免修改原始日期
        if (isEnd) {
          // 对结束时间加一天，以确保区间包括结束日期当天
          formattedDate.setDate(formattedDate.getDate() + 1);
        }
        const year = formattedDate.getFullYear();
        const month = ('0' + (formattedDate.getMonth() + 1)).slice(-2);
        const day = ('0' + formattedDate.getDate()).slice(-2);
        return `${year}-${month}-${day}`;
      }
      return null;
    },
    //默认时间
    defaultTime() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
      end.setTime(end.getTime());
      this.value2 = [start, end]; // 重置为最近一周
      this.getTime()
    },

    /**
     * 全选功能
     *
     */
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log("******************************", val);
    },

    /**
     *  改变页码
     */
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.getClientList();
    },
    /**
     * 翻页
     */
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.getClientList();
    },
    confirmUserId(ids) {
      const resourceIds = this.multipleSelection.map(item => item.resourceId);
      console.log(resourceIds);
      this.assignResources(resourceIds, ids);
    },
    async assignResources(resourceIds, userIds) {
      const {data: res} = await this.$http.put("/shiftClient/assignResources", {
        resourceIds: resourceIds,
        userIds: userIds
      });
      if (res > 0) {
        this.getClientList();
        this.$message.success(`分配成功，共成功 ${res} 个客户`);
      } else {
        this.$message.error('分配失败，没有客户被成功分配');
      }
    }
  },
  created() {
    this.getAccountNameList();
    this.defaultTime();
    this.searchClient();
    this.getAllIndustryList();
    this.getAllClientType();
    this.selectUser();
  },

};
</script>

<style scoped>
.hint {
  margin-left: 2vh;
  font-weight: 400;
  font-size: 12px;
  color: red;
}

.dataDict {
  border: none;
  background-color: #fff;
  position: absolute;
  padding: .8vh 0;
  left: 17.2vh;
  font-size: 18px;
}

.popups {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0%;
  left: 0%;
  background-color: #00000042;
  z-index: 100;
}

.popups .el-main {
  background-color: #fff;
  margin: 15vh auto;
}

.popups .el-main .header {
  display: flex;
  justify-content: center;
  margin-bottom: 2vh;
}

.popups .el-main .header button {
  flex-shrink: 0; /* 防止收缩 */
  font-size: 3vh;
  height: 4.6vh;
  border: none;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-row .el-col {
  font-size: 14px;
}

.el-row .el-col label {
  color: #5e6d82;
}
</style>
